import sys
from flask import Flask, request, jsonify, g, Response, stream_with_context
from sqlmodel import SQLModel
from crudUser import crudUser
from treeKernel import ftree
from classDef import get_session,engine
from Agent import NoteAgent
import warnings
from visitPCfs import visitPCfs  # 确保导入visitPCfs类
warnings.filterwarnings("ignore", category=DeprecationWarning)
from classDef import docker_init
docker_init()
app = Flask(__name__)

@app.before_request
def before_request():
    g.db_session = get_session()

@app.teardown_request
def teardown_request(exception):
    db_session = getattr(g, 'db_session', None)
    if db_session is not None:
        db_session.close()

# 简单初始化示例
# 如果您的项目需要更完整的初始化或数据库连接，可在此加入其他逻辑
global_tree = ftree()
cruduser = crudUser(global_tree)

# 创建visitPCfs对象
visit_aff_be = visitPCfs()

# 用字典来存储用户对应的NoteAgent实例
user_agents = {}

@app.route('/mdtree/addUser', methods=['POST'])
def add_user():
    """
    示例：添加用户
    请求方式：POST
    请求参数(JSON)：{"user": "username"}
    """
    data = request.get_json()
    user = data.get('user', '')
    result = cruduser.addUser(user)
    return jsonify({"result": result})

@app.route('/mdtree/createSpace', methods=['POST'])
def create_space():
    """
    示例：创建空间
    请求方式：POST
    请求参数(JSON)：{
        "user": "username",
        "a_spaceId": "your_space_id",
        "newSpaceName": "空间名称"
    }
    """
    data = request.get_json()
    user = data.get('user', '')
    a_spaceId = data.get('a_spaceId', '')
    newSpaceName = data.get('newSpaceName', '')
    result = cruduser.createSpace(user, a_spaceId, newSpaceName)
    return jsonify(result)

@app.route('/mdtree/createDoc', methods=['POST'])
def create_doc():
    """
    示例：创建文档
    请求方式：POST
    请求参数(JSON)：{
        "user": "username",
        "a_spaceId": "your_space_id",
        "a_docId": "your_doc_id",
        "newDocName": "文档名称"
    }
    """
    data = request.get_json()
    user = data.get('user', '')
    a_spaceId = data.get('a_spaceId', '')
    a_docId = data.get('a_docId', '')
    newDocName = data.get('newDocName', '')
    result = cruduser.createDoc(user, a_spaceId, a_docId, newDocName)
    return jsonify(result)

@app.route('/mdtree/renameDoc', methods=['POST'])
def rename_doc():
    """
    示例：重命名文档
    请求方式：POST
    请求参数(JSON)：{
        "user": "username",
        "a_spaceId": "your_space_id",
        "a_docId": "要重命名的docId",
        "newDocName": "新文件名称"
    }
    """
    data = request.get_json()
    user = data.get('user', '')
    a_spaceId = data.get('a_spaceId', '')
    a_docId = data.get('a_docId', '')
    newDocName = data.get('newDocName', '')
    result = cruduser.renameDoc(user, a_spaceId, a_docId, newDocName)
    return jsonify(result)

@app.route('/mdtree/deleteDoc', methods=['POST'])
def delete_doc():
    """
    示例：删除文档
    请求方式：POST
    请求参数(JSON)：{
        "user": "username",
        "a_spaceId": "your_space_id",
        "a_docId": "要删除的docId"
    }
    """
    data = request.get_json()
    user = data.get('user', '')
    a_spaceId = data.get('a_spaceId', '')
    a_docId = data.get('a_docId', '')
    result = cruduser.deleteDoc(user, a_spaceId, a_docId)
    return jsonify(result)

@app.route('/mdtree/writeDoc', methods=['POST'])
def write_doc():
    """
    示例：写文档内容
    请求方式：POST
    请求参数(JSON)：{
        "user": "username",
        "a_spaceId": "your_space_id",
        "a_docId": "要写入的docId",
        "content": "写入的文本"
    }
    """
    data = request.get_json()
    user = data.get('user', '')
    a_spaceId = data.get('a_spaceId', '')
    a_docId = data.get('a_docId', '')
    content = data.get('content', '')
    result = cruduser.writeDoc(user, a_spaceId, a_docId, content)
    return jsonify(result)

@app.route('/mdtree/renameSpace', methods=['POST'])
def rename_space():
    """
    示例：重命名空间
    请求方式：POST
    请求参数(JSON)：{
        "user": "username",
        "a_spaceId": "要重命名的spaceId",
        "newSpaceName": "新空间名称"
    }
    """
    data = request.get_json()
    user = data.get('user', '')
    a_spaceId = data.get('a_spaceId', '')
    newSpaceName = data.get('newSpaceName', '')
    result = cruduser.renameSpace(user, a_spaceId, newSpaceName)
    return jsonify(result)

@app.route('/mdtree/deleteSpace', methods=['POST'])
def delete_space():
    """
    示例：删除空间
    请求方式：POST
    请求参数(JSON)：{
        "user": "username",
        "a_spaceId": "要删除的spaceId"
    }
    """
    data = request.get_json()
    user = data.get('user', '')
    a_spaceId = data.get('a_spaceId', '')
    result = cruduser.deleteSpace(user, a_spaceId)
    return jsonify(result)

@app.route('/mdtree/moveDoc', methods=['POST'])
def move_doc():
    """
    示例：移动文档
    请求方式：POST
    请求参数(JSON)：{
        "user": "username",
        "a_spaceId": "源spaceId",
        "a_docId": "源docId",
        "dest_a_spaceId": "目标spaceId",
        "dest_a_docId": "目标docId"
    }
    """
    data = request.get_json()
    user = data.get('user', '')
    a_spaceId = data.get('a_spaceId', '')
    a_docId = data.get('a_docId', '')
    dest_a_spaceId = data.get('dest_a_spaceId', '')
    dest_a_docId = data.get('dest_a_docId', '')
    result = cruduser.moveDoc(user, a_spaceId, a_docId, dest_a_spaceId, dest_a_docId)
    return jsonify(result)

@app.route('/mdtree/copyDoc', methods=['POST'])
def copy_doc():
    """
    示例：复制文档
    请求方式：POST
    请求参数(JSON)：{
        "user": "username",
        "a_spaceId": "源spaceId",
        "a_docId": "源docId",
        "dest_a_spaceId": "目标spaceId",
        "dest_a_docId": "目标docId"
    }
    """
    data = request.get_json()
    user = data.get('user', '')
    a_spaceId = data.get('a_spaceId', '')
    a_docId = data.get('a_docId', '')
    dest_a_spaceId = data.get('dest_a_spaceId', '')
    dest_a_docId = data.get('dest_a_docId', '')
    result = cruduser.copyDoc(user, a_spaceId, a_docId, dest_a_spaceId, dest_a_docId)
    return jsonify(result)

# New methods
@app.route('/mdtree/agentpermission', methods=['POST'])
def agentPerm():
    data = request.get_json()
    user = data.get('user', '')
    a_spaceId = data.get('a_spaceId', '')
    a_docId = data.get('a_docId', '')
    permChar= data.get('permChar','')
    method = data.get('method','') 
    result = cruduser.agentPerm(user, a_spaceId,a_docId,permChar,method)
    return jsonify({"result": result})


@app.route('/share', methods=['POST'])
def share():
    data = request.get_json()
    user = data.get('user', '')
    a_spaceId = data.get('a_spaceId', '')
    a_docId = data.get('a_docId', '')
    permChar = data.get('permChar', '')
    share_user = data.get('share_user', '')
    result = cruduser.share(user, a_spaceId, a_docId, permChar, share_user)
    return jsonify({"result": result})

@app.route('/mdtree/literalsearch', methods=['POST'])
def literal_search():
    """
    示例：字面量搜索
    请求方式：POST
    请求参数(JSON)：{
        "user": "username",
        "query": "搜索查询",
        "useRegex": true 或 false
    }
    """
    data = request.get_json()
    user = data.get('user', '')
    query = data.get('query', '')   
    efrt = data.get('efrt', '')
    affSpaceId = data.get('affSpaceId', '')
    useRegex = data.get('useRegex', False)
    result = cruduser.literalSearch(user, query, efrt, affSpaceId, useRegex)
    print(result)
    sys.stdout.flush()
    return jsonify(result)
@app.route('/mdtree/semanticsearch', methods=['POST'])
def semantic_search():
    """
    示例：语义搜索
    请求方式：POST
    请求参数(JSON)：{
        "user": "username",
        "query": "搜索查询"
    }
    """
    data = request.get_json()
    user = data.get('user', '')
    query = data.get('query', '')
    efrt = data.get('efrt', '')
    affSpaceId = data.get('affSpaceId', '')
    result = cruduser.semanticSearch(user, query,efrt,affSpaceId)
    print(result)
    sys.stdout.flush()
    return jsonify(result)

@app.route('/mdtree/noteagent', methods=['POST'])
def noteagent():
    """
    为每个用户维护独立的NoteAgent实例
    请求参数(JSON)：{
        "user": "username",
        "task": "用户要给agent的指令" 
    }
    """
    data = request.get_json()
    user = data.get('user', '')
    task = data.get('task', '')
    
    # 如果该用户还没有对应的NoteAgent实例，则创建一个
    if user not in user_agents:
        user_agents[user] = NoteAgent()
        
    # 使用用户对应的NoteAgent实例
    agent = user_agents[user]
    
    # 使用流式响应，文本传输
    return Response(stream_with_context(agent.main(user, task)), mimetype="text/plain")

@app.route('/affine/readDoc', methods=['POST'])
def read_doc():
    """
    示例：读取文档
    请求方式：POST
    请求参数(JSON)：{
        "user": "username",
        "a_spaceId": "your_space_id",
        "a_docId": "your_doc_id"
    }
    """
    data = request.get_json()
    user = data.get('user', '')
    a_spaceId = data.get('a_spaceId', '')
    a_docId = data.get('a_docId', '')
    result = visit_aff_be.readDoc(user, a_spaceId, a_docId)
    return jsonify(result)

@app.route('/mdtree/noteagent_s', methods=['POST'])
def noteagent_s():
    data = request.get_json()
    user = data.get('user', '')
    task = data.get('task', '')
    streamType = data.get('streamtype', 2)
    # 如果该用户还没有对应的NoteAgent实例，则创建一个
    if user not in user_agents:
        user_agents[user] = NoteAgent()
    # 使用用户对应的NoteAgent实例
    agent = user_agents[user]

    # 使用流式响应，文本传输
    return Response(
        stream_with_context(agent.mainS(user, task,streamType)),
        mimetype="text/plain"
    )

@app.route('/mdtree/permission', methods=['POST'])
def permission():
    data = request.get_json()
    user = data.get('user', '')
    nodeid = int(data.get('perm_nodeid', ''))
    result = data.get('result', '')
    if user not in user_agents:
        user_agents[user] = NoteAgent()
    # 使用用户对应的NoteAgent实例
    agent = user_agents[user]
    print("permission_server",agent.tree.pendingPermissions,"gotdata",data)
    sys.stdout.flush()
    if (user,nodeid) in agent.tree.pendingPermissions:
        print(user,nodeid,"in pending dict:",agent.tree.pendingPermissions)
        sys.stdout.flush()
        agent.tree.pendingPermissions[(user,nodeid)]=result
        return jsonify({"success":nodeid,"message":"success"})
    else:
        print(agent.tree.pendingPermissions)
        return jsonify({"success":-1,"message":"nodeid not in pendingPermissions set"})
# 可以添加一个清理不活跃用户实例的函数
def cleanup_inactive_agents():
    """
    清理长时间不活跃的用户实例
    可以基于时间戳或其他策略来实现
    """
    pass

if __name__ == '__main__':
    # 开发环境下，建议开启 debug 模式便于调试
    # 生产环境请关闭 debug，并使用更安全的配置
    app.run(host='0.0.0.0', port=5000, debug=True) 